import numpy as np
from sklearn.metrics import f1_score

class ThresholdOptimizer:
    def __init__(self, model, X_val, y_val):
        self.model = model
        self.X_val = X_val
        self.y_val = y_val
        
    def find_optimal_threshold(self):
        """寻找最佳分类阈值"""
        y_proba = self.model.predict_proba(self.X_val)[:, 1]
        thresholds = np.linspace(0.1, 0.9, 50)
        
        best_threshold = 0.5
        best_score = -1
        
        for threshold in thresholds:
            y_pred = (y_proba >= threshold).astype(int)
            current_score = f1_score(self.y_val, y_pred)
            if current_score > best_score:
                best_score = current_score
                best_threshold = threshold
                
        return best_threshold 